import app from './app'; // 导入在 app.ts 中配置好的 Express 应用实例
import { connectDB, sequelize } from './config/database';
// 导入所有需要进行关联的模型
import User from './models/User';
import InterestTag from './models/InterestTag';
import Circle from './models/Circle';
import CirclePost from './models/CirclePost';
import CircleComment from './models/CircleComment';
import CirclePostLike from './models/CirclePostLike';
import CircleCommentLike from './models/CircleCommentLike';

const port = process.env.PORT || 5000;

// 连接数据库并启动服务器
const startServer = async () => {
    try {
        await connectDB();

        // 初始化模型关联
        User.associate({ InterestTag, Circle, CirclePost, CircleComment, CirclePostLike, CircleCommentLike });
        InterestTag.associate({ User });
        Circle.associate({ User, CirclePost, CircleComment });
        CirclePost.associate({ User, Circle, CirclePostLike });
        CircleComment.associate({ User, CirclePost, CircleComment, CircleCommentLike });
        CirclePostLike.associate({ User, CirclePost });
        CircleCommentLike.associate({ User, CircleComment });

        console.log('Database connection successful, models associated.');

        // 同步数据库（如果需要的话，通常在迁移工具中处理）
        // await sequelize.sync({ alter: true });
        // console.log('Database synchronized.');

        app.listen(port, () => {
            console.log(`Backend server running on port ${port}`);
        });
    } catch (error) {
        console.error('Failed to start backend server:', error);
        process.exit(1); // 启动失败时退出进程
    }
};

startServer(); 